<template>
  <el-select
    v-model="selectedProduct"
    placeholder="选择产品版本"
    @change="handleProductChange"
    class="product-selector"
  >
    <el-option
      v-for="product in products"
      :key="`${product.name}-${product.version}`"
      :label="product.displayName || `${product.name} ${product.version}`"
      :value="`${product.name}-${product.version}`"
    >
      <span>{{ product.displayName || `${product.name} ${product.version}` }}</span>
      <el-tag
        v-if="product.version"
        size="small"
        type="info"
        class="ml-2"
      >
        {{ product.version }}
      </el-tag>
    </el-option>
  </el-select>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useModulesStore } from '@/stores/modules'

const modulesStore = useModulesStore()

const selectedProduct = ref('')

// 计算属性
const products = computed(() => modulesStore.products)

// 监听产品变化，自动选择第一个产品
watch(products, (newProducts) => {
  if (newProducts.length > 0 && !selectedProduct.value) {
    const firstProduct = newProducts[0]
    selectedProduct.value = `${firstProduct.name}-${firstProduct.version}`
  }
}, { immediate: true })

const handleProductChange = (value) => {
  if (value) {
    const [name, version] = value.split('-')
    modulesStore.setProduct(name, version)
    modulesStore.fetchModules()
  }
}

onMounted(() => {
  modulesStore.fetchProducts()
})
</script>

<style scoped lang="scss">
.product-selector {
  min-width: 200px;

  :deep(.el-select__wrapper) {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.2);

    .el-input__inner {
      color: white;
    }

    .el-input__suffix {
      color: rgba(255, 255, 255, 0.8);
    }

    &.is-focus {
      background: rgba(255, 255, 255, 0.15);
      border-color: rgba(255, 255, 255, 0.3);
    }
  }

  :deep(.el-popper.is-dark) {
    background: rgba(0, 0, 0, 0.8);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
}
</style>